const get = (url, type_='json') => {
    console.log(`Fetching(GET) ${url}`);
    return fetch(url).then(resp => resp.text()).then(respText => {
        if (type_.toLowerCase() !== 'json') {
            return respText;
        }
        return JSON.parse(respText);
    }).catch(err => {
        console.log(`Fetching(GET) ${url} error: ${err}`);
        return null
    });
}

const post = (url, data, requestType='form', responseType='json') => {
    console.log(`Fetching(POST) ${url}`);
    let contentType = 'application/x-www-form-urlencoded';
    let payload = null;
    if (requestType === 'json') {
        contentType = 'application/json; charset=UTF-8';
        payload = JSON.stringify(data);
    } else if (requestType === 'form') {
        contentType = 'application/x-www-form-urlencoded; charset=UTF-8'
        payload = new URLSearchParams(data).toString();
    } else {
        console.log(`Not supported request type ${requestType}`);
        return null;
    }

    return fetch(url, {
        method: 'POST',
        body: payload,
        headers: {
            'Content-Type': contentType
        },
        credentials: 'same-origin',
    }).then(resp => {
        if (resp.status !== 200) {
            console.log(`Non-200 status for requesting ${url}`);
            return null;
        }
        return resp.text();
    }).then(respText => {
        if (respText == null) {
            return null;
        }
        if (responseType.toLowerCase() !== 'json') {
            return respText;
        }
        return JSON.parse(respText);
    }).catch(err => {
        console.log(`Fetch(POST) ${url} error: ${err}`);
        return null;
    });
}

export default {
    get: get,
    post: post,
}